import axios from "axios";
import { showToast } from "vant";
// axios基础配置
const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时时间
  // timeout: 10000,
})
import I18N from "@/i18n";
import { setItem } from "@/utils/utils";
// 请求拦截
axiosInstance.interceptors.request.use(
  (config) => {
    if (config) {
      // 在请求头里面加东西
      if (config.headers) {
        // let TOKEN = '5ac3a1f6-fa0f-4967-8019-fcc77560bfec'
        let TOKEN = localStorage.getItem("authtoken");
        if (TOKEN) {
          config.headers['authtoken'] = TOKEN;
        }
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)
axiosInstance.interceptors.response.use((response) => {
  if (response?.data?.code !== 0) {

    if (response?.data?.code == 13) {
      setItem('authtoken', "")
      showToast({
        message: I18N.global.t("DLGQ")
      })
    }
    if (response?.data?.code == 401) {
      // refresh(response);
    } else {
      showToast({
        duration: 500,
        message: response?.data?.message
      })
    }
  }
  return response;
},
  async (error) => {
    if (error.response.headers.authtoken) {
      localStorage.setItem("authtoken", error.response.headers.authtoken);
    }
    if (error.response.status == 401) {

    } else {
      if (error.response?.data?.code == 13) {
        setItem('authtoken', "")
        showToast({
          message: I18N.global.t("DLGQ")
        })
      }
      if (error.response?.data?.code == 401) {
        // refresh(response);
      } else {
        showToast({
          duration: 500,
          message: error.response?.data?.message
        })
      }
      return Promise.reject(error);
    }
  })

export default axiosInstance;